package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.common.Consts;
import com.github.aloxc.plugin.restplus.entity.Group;
import com.github.aloxc.plugin.restplus.entity.RestConfig;
import com.github.aloxc.plugin.restplus.i18n.I18Bundle;
import com.github.aloxc.plugin.restplus.navigator.RestServicesNavigator;
import com.intellij.openapi.project.Project;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
 *
 * @author leero
 */
public class GroupListener extends MouseAdapter implements ActionListener {
    private Project project;
    public GroupListener(Project project) {
        this.project = project;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        Component groupButton = (JButton)e.getSource();
        int x = e.getX();
        int y = e.getY() + 5;
        JPopupMenu menu = new JPopupMenu();
        //模块
        JMenuItem module = new JMenuItem(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.url.tree.show.module.text"));
        module.setName(Group.MODULE.getType());
        //请求方式
        JMenuItem method = new JMenuItem(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.url.tree.show.method.text"));
        method.setName(Group.METHOD.getType());
        module.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        method.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        module.setIcon(Consts.Icons.MODULE);
        method.setIcon(Consts.Icons.METHOD);
        RestConfig config = project.getComponent(RestServicesNavigator.class).getConfig();
        menu.add(module);
        menu.add(method);
        module.addActionListener(this);
        method.addActionListener(this);
        menu.show(groupButton, x, y);
        JMenuItem curItem = null;
        if (config == null) {
            return;
        }
        String group = Group.get().getType();
        if (module.getName().equals(group)) {
            curItem = module;
        } else {
            curItem = method;
        }
        curItem.setSelected(true);
        curItem.setIcon(Consts.Icons.CUR);
        curItem.setForeground(Consts.MAIN_COLOR);
        curItem.setBackground(Consts.COOKIE_BACKGROUND_COLOR);
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
        String groupType = ((JMenuItem) evt.getSource()).getName();
        Group.set(Group.getByType(groupType));
        new RefreshListener(project).doRefreshProject();
    }
}
